package com.fyy.shortvideo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.View;

public class ProgressView extends View {
	/** 进度条 */
	private Paint mProgressPaint;
	/** 最长时长 */
	private int mMax;
	/** 进度 */
	private int mProgress;
	private boolean isRemove;
	private boolean isDetach = false;

	public ProgressView(Context Context, AttributeSet Attr) {
		super(Context, Attr);
		init();
	}

	private void init() {
		mProgressPaint = new Paint();
		mProgressPaint.setAntiAlias(true);
		mProgressPaint.setColor(Color.GREEN);
		mProgressPaint.setStyle(Paint.Style.FILL);
	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		isDetach = true;
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		isDetach = false;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if (!isDetach) {
			return;
		}
		canvas.save();
		if (mProgress == 0) {
			setRemove(true);
			return;
		} else {
			setRemove(false);
		}
		canvas.translate(getPaddingLeft(), getPaddingTop());
		final int width = getMeasuredWidth(), height = getMeasuredHeight();
		int progressLength = (int) ((mProgress / (mMax * 1.0f)) * (width / 2)); // 清屏
		if (isRemove) {
			mProgressPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
			canvas.drawPaint(mProgressPaint);
		} else {
			mProgressPaint.setXfermode(new PorterDuffXfermode(Mode.SRC));
			canvas.drawRect(progressLength, 0, width - progressLength, height,
					mProgressPaint);
		}
		canvas.restore();
	}

	public void setMax(int max) {
		this.mMax = max;
	}

	public void setProgress(int progress) {
		this.mProgress = progress;
		postInvalidate();
	}

	public void setRemove(boolean isRemove) {
		this.isRemove = isRemove;
	}
}
